<?php
class AudiencesController extends AppController {
	var $name = 'Audiences';
	var $uses = array('Survey', 'User');
	
  	var $paginate = array(
		'Survey' => array(
			'order' => array('Survey.created' => 'DESC'),
			'group' => array('Survey.id')
		)
	);
	
	/**
	 * Displays the audience portal home page
	 * 
	 * @return 
	 */
	function index() {
		//Get the data for my surveys and available surveys
		$this->_my_surveys();
		$this->_available_surveys();
	}
	
	/**
	 * Search surveys
	 * 
	 * @return 
	 */
	function search_surveys() {
		//Get the current user
		$user = $this->Auth->user();
		$userId = $user['User']['id'];
		
		//Filter by SurveysUser
		$this->Survey->Behaviors->attach('Containable');
		$this->Survey->bindModel(array('hasOne' => array('SurveysUser')));
		
		//Construct a sub query that filters by surveys this user has not registered for
		$conditionsSubQuery['SurveysUser2.user_id'] = $userId;
		$dbo = $this->Survey->getDataSource();
		$subQuery = $dbo->buildStatement(
		    array(
		        'fields' => array('SurveysUser2.survey_id'),
		        'table' => $dbo->fullTableName($this->Survey->SurveysUser),
		        'alias' => 'SurveysUser2',
		        'limit' => null,
		        'offset' => null,
		        'joins' => array(),
		        'conditions' => $conditionsSubQuery,
		        'order' => null,
		        'group' => null
		    ),
		    $this->Survey->SurveysUser
		);
		$subQuery = ' Survey.id NOT IN (' . $subQuery . ') ';
		$subQueryExpression = $dbo->expression($subQuery);
		
		//Set find parameters
		$conditions = array('Survey.isDeleted' => 0, 'SurveyType.type != ' => 'Incomplete', $subQueryExpression);
		$fields = array('Survey.id', 'Survey.name', 'Survey.uuid', 'SurveyType.type');
		$order = array('Survey.created DESC');
		$contain = array('SurveysUser','SurveyType');
		$limit = 50;
		$group = array('Survey.id');
		
		$surveys = $this->_getSurveys($conditions, $fields, $order, $contain, $limit, $group, true);
		$this->set('surveys', $surveys);
	}
	
	/**
	 * Gets all surveys that this user is registered for
	 * 
	 * @return 
	 */
	function my_surveys() {
		//Get the current user
		$user = $this->Auth->user();
		$userId = $user['User']['id'];
		
		//Filter by SurveysUser
		$this->Survey->Behaviors->attach('Containable');
		$this->Survey->bindModel(array('hasOne' => array('SurveysUser')));
		
		//Set find parameters
		$conditions = array('Survey.isDeleted' => 0, 'SurveyType.type != ' => 'Incomplete', 'SurveysUser.user_id' => $userId);
		$fields = array('Survey.id', 'Survey.name', 'Survey.uuid', 'SurveyType.type');
		$order = array('Survey.created DESC');
		$contain = array('SurveysUser','SurveyType');
		$limit = 50;
		$group = array('Survey.id');
		
		$surveys = $this->_getSurveys($conditions, $fields, $order, $contain, $limit, $group, true);
		$this->set('surveys', $surveys);
	}
	
	/**
	 * Gets all surveys of the type 'Available'
	 * 
	 * @return 
	 */
	function available_surveys() {
		//Clear out the name and uuid filters
		$this->Session->write($this->name.'.searchAudName', "");
		$this->Session->write($this->name.'.searchAudUUID', "");
		//Set the survey type filter to available
		$this->Session->write($this->name.'.searchAudType', 'Available');
		
		//Redirect to the search surveys page
		$this->redirect(array('controller' => 'audiences', 'action' => 'search_surveys'));
	}
	
	/**
	 * Gets the top five surveys this user is registered for
	 * 
	 * @return 
	 */
	function _my_surveys() {
		//Get the current user
		$user = $this->Auth->user();
		$userId = $user['User']['id'];
		
		//Filter by SurveysUser
		$this->Survey->Behaviors->attach('Containable');
		$this->Survey->bindModel(array('hasOne' => array('SurveysUser')));
		
		//Set find parameters
		$conditions = array('Survey.isDeleted' => 0, 'SurveysUser.user_id' => $userId);
		$fields = array('Survey.id', 'Survey.name');
		$order = array('Survey.created DESC');
		$contain = 'SurveysUser';
		$limit = 5;
		$group = array('Survey.id');
		
		$my_surveys = $this->_getSurveys($conditions, $fields, $order, $contain, $limit, $group, false);
		$this->set('my_surveys', $my_surveys);
	}
	
	/**
	 * Gets the last five created available surveys
	 * 
	 * @return 
	 */
	function _available_surveys() {
		//Get the current user
		$user = $this->Auth->user();
		$userId = $user['User']['id'];
		
		//Filter by SurveysUser
		$this->Survey->Behaviors->attach('Containable');
		$this->Survey->bindModel(array('hasOne' => array('SurveysUser')));
		
		//Construct a sub query that filters by surveys this user has not registered for
		$conditionsSubQuery['SurveysUser2.user_id'] = $userId;
		$dbo = $this->Survey->getDataSource();
		$subQuery = $dbo->buildStatement(
		    array(
		        'fields' => array('SurveysUser2.survey_id'),
		        'table' => $dbo->fullTableName($this->Survey->SurveysUser),
		        'alias' => 'SurveysUser2',
		        'limit' => null,
		        'offset' => null,
		        'joins' => array(),
		        'conditions' => $conditionsSubQuery,
		        'order' => null,
		        'group' => null
		    ),
		    $this->Survey->SurveysUser
		);
		$subQuery = ' Survey.id NOT IN (' . $subQuery . ') ';
		$subQueryExpression = $dbo->expression($subQuery);
		
		//Set find parameters
		$conditions = array('Survey.isDeleted' => 0, 'SurveyType.type' => 'Available', $subQueryExpression);
		$fields = array('Survey.id', 'Survey.name');
		$order = array('Survey.created DESC');
		$contain = array('SurveysUser','SurveyType');
		$limit = 5;
		$group = array('Survey.id');
		
		$available_surveys = $this->_getSurveys($conditions, $fields, $order, $contain, $limit, $group, false);
		$this->set('available_surveys', $available_surveys);
	}
	
	function show_all_my_surveys() {
		//Clear search filters
		$this->Session->write($this->name.'.searchAudName', "");
		$this->Session->write($this->name.'.searchAudUUID', "");
		$this->Session->write($this->name.'.searchAudType', "");
		
		$this->redirect(array('controller' => 'audiences', 'action' => 'my_surveys'));
	}
	
	function show_all_search_surveys() {
		//Clear search filters
		$this->Session->write($this->name.'.searchAudName', "");
		$this->Session->write($this->name.'.searchAudUUID', "");
		$this->Session->write($this->name.'.searchAudType', "");
		
		$this->redirect(array('controller' => 'audiences', 'action' => 'search_surveys'));
	}
	
	/**
	 * Get the surveys matching the specified options
	 * 
	 * @param object $conditions
	 * @param object $fields
	 * @param object $order
	 * @param object $contain
	 * @param object $limit
	 * @param object $group
	 * @param object $isSearch
	 * @return 
	 */
	function _getSurveys($conditions, $fields, $order, $contain, $limit, $group, $isSearch) {
		
		//Initialize variables
		$searchName = "";
		$searchUUID = "";
		$searchType = "";		
		$this->set('searchName', '');
		$this->set('searchUUID', '');
		$this->set('searchType', '');
		$display = false;
		$filters = array();
		$surveys = array();
		
		if($isSearch) {
			//Get the search term either from the post data or the session 
		    if(!empty($this->data))
			{
		        $searchName = trim($this->data['Survey']['name']);
				$searchUUID = trim($this->data['Survey']['uuid']);
				$searchType = trim($this->data['SurveyType']['type']);
			}
			elseif($this->Session->check($this->name.'.searchAudName') || $this->Session->check($this->name.'.searchAudUUID')
					|| $this->Session->check($this->name.'.searchAudType'))
			{
				if($this->Session->check($this->name.'.searchAudName'))
		        	$searchName = $this->Session->read($this->name.'.searchAudName');
				if($this->Session->check($this->name.'.searchAudUUID'))
		        	$searchUUID = $this->Session->read($this->name.'.searchAudUUID');
				if($this->Session->check($this->name.'.searchAudType'))
		        	$searchType = $this->Session->read($this->name.'.searchAudType');
			}
			
		    if(!empty($searchName)) {
		    	//Set up the search filters
		        $filters = array('lower(Survey.name) LIKE' => '%'.low($searchName).'%', 'Survey.isDeleted' => '0');
		        $this->Session->write($this->name.'.searchAudName', $searchName);
				$this->set('searchName', $searchName);
		    }
			
			if(!empty($searchUUID)) {
		    	//Set up the search filters
				$key = 'SUBSTRING(Survey.uuid,2,8) LIKE';
				$value = '%'.$searchUUID.'%';
				$uuidFilters = array($key=>$value);
				$filters = array_merge($filters, $uuidFilters);
				
		        $this->Session->write($this->name.'.searchAudUUID', $searchUUID);
				$this->set('searchUUID', $searchUUID);
		    }
			
			if(!empty($searchType)) {
		    	//Set up the search filters
				$key = 'SurveyType.type';
				$value = $searchType;
				$typeFilters = array($key=>$value);
				$filters = array_merge($filters, $typeFilters);
				
		        $this->Session->write($this->name.'.searchAudType', $searchType);
				$this->set('searchType', $searchType);
		    }
			
			//Merge the search conditions with those passed as a parameter
			$conditions = array_merge($conditions, $filters);
			
			//Get the paginated results
			$this->paginate['Survey'] = compact('conditions', 'fields', 'order', 'contain', 'limit', 'group');
			$surveys = $this->paginate('Survey');
			
		} else {
			//Get all surveys matching the specified conditions
			$surveys = $this->Survey->find('all',
				array(
					'conditions' => $conditions,
					'fields' => $fields,
					'order' => $order,
					'contain' => $contain,
					'limit' => $limit,
					'group' => $group
			));
		}
		
		//If the surveys variable is not empty, display results
		if(!empty($surveys)) {
			$display = true;
		}
		$this->set('display', $display);
		
	    return $surveys;
	}
}
?>
